package com.fare.fdc.action;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.util.PDFTextStripper;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.stereotype.Controller;

import com.fare.taluo.BaseFdcAction;
import com.fare.taluo.application.plane.city.PortApplication;
import com.fare.taluo.application.plane.flight.FlightInfoApplication;
import com.fare.taluo.vo.core.FlightInfoVO;
import com.fare.taluo.vo.core.PortEntityVO;

@Controller("shanHangParseAction")
@Namespace("/")
public class ShanHangParseAction extends BaseFdcAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = -7678730266650482171L;
	@Resource(name="flightInfoApplication")
	private FlightInfoApplication application;
	@Resource(name="portApplication")
	private PortApplication portApplication;
	private Map<String,PortEntityVO> voMap;
	private  String uploadFileSC;
	
	
	public void pdfParse() throws Exception{
//		String pdfPath = "c://山东航空.pdf";
		InputStream input = null;	
		PDDocument document = null;
		try {
            if(null!=uploadFileSC){
            	input = new FileInputStream(uploadFileSC);
            	
            }else{
            	super.toJSONOut("{\"result\":\"解析失败!\"}");
            	}
			
           voMap = portApplication.findPortEntityToMapByName();
			// 加载 pdf 文档

			document = PDDocument.load(input);

			/** 文档属性信息 **/

			PDDocumentInformation info = document.getDocumentInformation();

			// 获取内容信息
            String companyCode = "SC";
            Pattern pattern = Pattern.compile("^(\\d+)(.*)");
			PDFTextStripper pts = new PDFTextStripper();
			pts.setStartPage(8);
			pts.setEndPage(23);
			String oldContent = pts.getText(document);
			String text0 = oldContent.split("出发 到达 起飞 降落 航班 班期 经停")[1];
			String newContent = text0.replaceAll("仅供参考，以实际查询结果为准，如有变动，恕不另行通知。", "")
					.replaceAll("24小时服务热线 山东 96777 全国 400-60-96777", "").replaceAll("\r\n", "-");
			String newData=newContent.replaceAll("-","").replaceAll("       ", " ").replaceAll("  "," ").replaceAll("周 ", "周").replaceAll("月 ", "月");
			  int n=0;
			  int anySize=0;
			  String saveHead="";
			  String testString="";
			  int k=0;
			  FlightInfoVO vo = new FlightInfoVO();
			  List<String > newRecords=new ArrayList<String>(); 
			for(int m=0;m<newData.length();m++){
			//	System.out.println("k="+k);
				if(newData.charAt(m)=='每' || newData.charAt(m)=='周'){//定位【每】【周】的位置
				//	System.out.println("m="+m);
					String s=newData.substring(m);
					int h=s.indexOf(" ",s.indexOf(" ")+1);//定位【每】【周】的位置后的两个空格的位置，并在此位置下断开字符,组成String
					anySize=m+h;
					
				//	System.out.println("h="+anySize);
					testString=newData.substring(n,anySize).trim();
					
					/*
					 * //因为PDF合并了表格，现在重新把【出发城市】和【到达城市】加载到每一条航线上去
					 * 1.判断是否为数字开头，如果不是说明已经有【出发城市】和【到达城市】，而且把【出发城市】和【到达城市】拿出来，准备给下一条航线使用
					 * 2.如果是数字开头，则重组航线信息，把【出发城市】和【到达城市】重新加载到里面去
					*/
					if(pattern.matcher(testString).matches()!=true){
						k=testString.indexOf(" ",testString.indexOf(" ")+1);
						saveHead=testString.substring(0, k);
					}
					if(pattern.matcher(testString).matches()==true){
						testString=saveHead+" "+testString;
					}
				//	System.out.println("saveHead=="+saveHead);
					newRecords.add(testString);
					n=anySize;
				//	System.out.println("testString="+testString);
					
				}
				
			}
		//	System.out.println("newRecords=="+newRecords);
			//组装成VO，并插入到数据库中
			for(int t=0;t<newRecords.size();t++){
				Date nows=new Date();
				String[] newrecoreds=newRecords.get(t).split(" ");
				if(newrecoreds[0].equals("北京")){
					vo.setFromCityName(newrecoreds[0]+"(PEK)");//出发城市
				}else{
					vo.setFromCityName(newrecoreds[0]);
				}
				if(newrecoreds[1].equals("北京")){
					vo.setToCityName(newrecoreds[1]+"(PEK)");
				}else{
					vo.setToCityName(newrecoreds[1]);//到达城市
				}
				
				vo.setFlightStartTime(newrecoreds[2]);//出发时间
				vo.setFlightEndTime(newrecoreds[3]);//到达时间
				vo.setFlightNo(newrecoreds[4]);//航班号
				if(newrecoreds[5].equals("每日")){
					vo.setFrequence("1234567");
				}else if(newrecoreds[5].indexOf("（")!=-1 && newrecoreds[5].indexOf("）")!=-1){
					int begS=newrecoreds[5].indexOf("（");
					int endS=newrecoreds[5].indexOf("）");
					String effectTime=newrecoreds[5].substring(begS+1, endS).replace("（", "");
					if(effectTime.indexOf("日")==-1 && effectTime.indexOf("月")==-1 ){
						vo.setEffectStartTime(effectTime.substring(0, 4));
						vo.setEffectEndTime(effectTime.substring(4));
					}else{
					String [] effectSandETime=effectTime.split("日");
					vo.setEffectStartTime(effectSandETime[0].replace("月","."));
					vo.setEffectEndTime(effectSandETime[1].replace("月","."));
					}
					vo.setFrequence(newrecoreds[5].substring(1, begS)); 
				}else {
					vo.setFrequence(newrecoreds[5].substring(1));
				}
				if(newrecoreds[6] !=null && !newrecoreds[6].equals("无")){
					vo.setStopCity(newrecoreds[6]);//经停城市
				}
				vo.setCompanyCode("SC");
				vo.setCompanyName("山东航空");
				vo.setEntryTime(nows);
				//排除一些不存在的航班，例如：国际航班【大阪】
				
				if(isDisplay(newrecoreds[0])){
					String fromCity=voMap.get(newrecoreds[0]).getPortCode();
					String areaCode=voMap.get(newrecoreds[0]).getAreaCode();
					String areaName=voMap.get(newrecoreds[0]).getAreaName();
					vo.setFromCity(fromCity);
					vo.setAreaCode(areaCode);
					vo.setAreaName(areaName);
				}
				if(isDisplay(newrecoreds[1])){
					String toCity=voMap.get(newrecoreds[1]).getPortCode();
					vo.setToCity(toCity);
				}
					

				
				try{
					 application.save(vo);
				}catch (Exception e) {
					e.printStackTrace();
				}
				
			}
			super.toJSONOut("{\"result\":\"解析成功!\"}");
			System.out.println("success");
		} catch (Exception e){
			e.printStackTrace();
			super.toJSONOut("{\"result\":\"解析失败!请通知管理员\"}");
		} finally {

			if (null != input)
				input.close();
			if (null != document)
				document.close();

		}
	}
	
	public boolean isDisplay(String cityname){
		boolean flag = false;
		PortEntityVO portEntityVo =new  PortEntityVO();
		portEntityVo=portApplication.findPortEntityByCityName(cityname);
		if(portEntityVo !=null && !portEntityVo.equals("") ){
			flag=true;
		}
		
		return flag;
	}
	
	public  boolean isNumeric(String str){
	    Pattern pattern = Pattern.compile("[0-9]*");
	    return pattern.matcher(str).matches();   
	 } 

	public String getUploadFileSC() {
		return uploadFileSC;
	}

	public void setUploadFileSC(String uploadFileSC) {
		this.uploadFileSC = uploadFileSC;
	}
	 
	public static void main(String[] args) throws Exception {
		new ShanHangParseAction().pdfParse();
	}
	
}
